package net.tngou.db.netty.http;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpRequest;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.Statement;
import net.tngou.db.manage.TML;
import net.tngou.db.query.Query;
import net.tngou.db.util.JavaVM;
import net.tngou.db.util.ResultSet;

/**
 * 查询接口
 * @author tngou@tngou.net
 *
 */
public class QueryAction {

	public void execute(ChannelHandlerContext ctx,Map<String, String> params)
	{
		
	
		String sql = params.get("sql");
		if(StringUtils.isEmpty(sql))
		{
			TngouHttpUtil.run(ctx, "{\"status\": false,\"rows\":[]}".getBytes());
			return;
		}
		if("schema".equals(sql.toLowerCase()))
		{
			List<Map<String, Object>> list = new TML().showTables();
			Object json = JSON.toJSON(list);
			TngouHttpUtil.run(ctx,json.toString().getBytes());
			return;
		}
		if(sql.toLowerCase().startsWith("desc"))
		{
			String[] sps = StringUtils.split(sql.toLowerCase(), " ");
			List<String> list=new ArrayList<String>();
			if(sps.length>1){
				list = new TML().descTable(sps[1]);
			}
			Object json = JSON.toJSON(list);
			TngouHttpUtil.run(ctx,json.toString().getBytes());
			return;
		}
		Query query= new Query();
		String page = params.get("page");
		String rows = params.get("rows");
		String limit="";
		if(NumberUtils.isNumber(page)&& NumberUtils.isNumber(rows))
		{
			int start=(Integer.parseInt(page)-1)*Integer.parseInt(rows);
			limit=" limit "+start+" , "+rows;
		}     
		ResultSet result = query.sql(sql+limit);
		JSONObject json = (JSONObject) JSON.toJSON(result);
		json.put("rows", json.get("list"));json.remove("list");
		if(json.getInteger("total")==0)
		{
			json.put("rows",new JSONArray());
		}
		TngouHttpUtil.run(ctx,json.toString().getBytes());
		return;
	}
	public void sysinfo(ChannelHandlerContext ctx) {	
		JavaVM vm = new JavaVM();
		
		JSONObject json = (JSONObject) JSON.toJSON(vm);
		TngouHttpUtil.run(ctx,json.toString().getBytes());
		return;
		
	}
}
